package jpa4azure.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;

import jpa4azure.type.Key;
import jpa4azure.type.TypeWrapper;
import jpa4azure.type.TypeWrapperFactory;

import com.windowsazure.samples.table.AzureTableEntity;
import com.windowsazure.samples.table.AzureTableEntityCollection;
import com.windowsazure.samples.table.AzureTableManager;
import com.windowsazure.samples.table.Filter;
import com.windowsazure.samples.table.IllegalFilterOperandType;

public class KeyQuery<T> extends CriteriaQueryAdaptor<T> {

	Key key;
	Class<T> c;
	AzureTableManager client;
	int limit = 1000;
	
	public KeyQuery(Class<T> c, Key key) {
		this.key = key;
		this.c = c;
	}

	@Override
	public TypedQuery<T> getTypedQuery(final AzureEntityManager aem) {
		final TypeWrapper type = TypeWrapperFactory.wrap(c);
		this.client = aem.getTableStorageClient();
		return new TypedQueryAdaptor<T>() {
			public List<T> getResultList() {
				List<T> list = new ArrayList<T>();
				AzureTableEntityCollection results = client.queryEntities(type.getTableName(), query(), limit);
				for (AzureTableEntity e : results)
					list.add((T)aem.convert(e));				
				return list;
			}
			
		};
		
	
	}

	public KeyQuery<T> take(int i) {
		this.limit = i;
		return this;
	}
	
	private Filter query() {
		try {
			return Filter.Equal("PartitionKey", key.getPartition());
		} catch (IllegalFilterOperandType e) {
			e.printStackTrace();
		}
		return null;
	}
	
	

}
